import { eventSource, event_types, setEditedMessageId } from "../../../script.js";
import { getContext } from "../../extensions.js";
import { delay } from '../../utils.js';

eventSource.on(event_types.MESSAGE_SENT, handleSentMessage);
eventSource.on(event_types.MESSAGE_RECEIVED, handleReceivedMessage);
eventSource.on(event_types.CHARACTER_MESSAGE_RENDERED, handleReceivedMessage);

async function doMesCut(start, count)
{
	for (let i = 0; i < count; i++)
	{
        let done = false;
        let mesToCut = $('#chat').find(`.mes[mesid=${start}]`);
        setEditedMessageId(start);
        eventSource.once(event_types.MESSAGE_DELETED, () => {
            done = true;
        });
        mesToCut.find('.mes_edit_delete').trigger('click', { fromSlashCommand: true });
        while (!done) {
            await delay(1);
        }
    }
}

async function handleSentMessage(messageId)
{
	const context = getContext();
    const message = context.chat[messageId];
    if(message && message.mes == '-roll')
    {
	    setTimeout(async () => {
		    await doMesCut(messageId - 1, 2);
	    }, 10);
    }
}

async function handleReceivedMessage(messageId)
{
	return true;
}